package com.atguigu.common.exception;

import com.atguigu.common.result.R;
import com.atguigu.common.result.ResponseEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author zwj
 * @create 2021-10-09 11:36
 */
@Slf4j
@RestControllerAdvice
public class UnifiedExceptionHandler {
    @ExceptionHandler(Exception.class)
    public R handleException(Exception e){
        log.error(e.getMessage(),e);
        return R.error().message(e.getMessage());
    }

    @ExceptionHandler(BadSqlGrammarException.class)
    public R handleBadSqlGrammarException(BadSqlGrammarException e){
        log.error(e.getMessage(), e);
        return R.setResult(ResponseEnum.BAD_SQL_GRAMMAR_ERROR);
    }

    @ExceptionHandler(BusinessException.class)
    public R handleBusinessException(BusinessException e){
        log.error(e.getMessage(), e);
        return R.error().message(e.getMessage()).code(e.getCode());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        log.error(e.getMessage(),e);
        return R.error().message(e.getMessage());
    }
    /**
     * Controller上一层相关异常
     */
//    @ExceptionHandler({
//            NoHandlerFoundException.class,
//            HttpRequestMethodNotSupportedException.class,
//            HttpMediaTypeNotSupportedException.class,
//            MissingPathVariableException.class,
//            MissingServletRequestParameterException.class,
//            TypeMismatchException.class,
//            HttpMessageNotReadableException.class,
//            HttpMessageNotWritableException.class,
//            MethodArgumentNotValidException.class,
//            HttpMediaTypeNotAcceptableException.class,
//            ServletRequestBindingException.class,
//            ConversionNotSupportedException.class,
//            MissingServletRequestPartException.class,
//            AsyncRequestTimeoutException.class
//    })
//    public R handleServletException(Exception e) {
//        log.error(e.getMessage(), e);
//        //SERVLET_ERROR(-102, "servlet请求异常"),
//        return R.setResult(ResponseEnum.SERVLET_ERROR);
//    }
}
